﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace DataAccessor.Tools
{
    public partial class FormPrimary
    {
        private void OpenDatabaseSettingForm()
        {
            FormDatabase form = new FormDatabase(_holistic);
            form.DatabaseCollectionChanged += new DatabaseCollectionChangedEventHandler(form_DatabaseCollectionChanged);
            form.DatabaseSettingChanged += new DatabaseChangedEventHandler(form_DatabaseSettingChanged);
            LoadSettingForm(form);
        }

        private void form_DatabaseSettingChanged(UCDatabase sender)
        {
            var node = treeHolistic.SelectedNode.Nodes[sender.Database.GetHashCode().ToString()];
            node.Text = sender.Database.Name;
        }

        private void form_DatabaseCollectionChanged()
        {
            var databaseNodes = treeHolistic.SelectedNode.Nodes;
            var removeDatabaseNodes = new List<TreeNode>();
            foreach (TreeNode databaseNode in databaseNodes)
            {
                if (!_holistic.Database.Any(d => d.GetHashCode().ToString().Equals(databaseNode.Name)))
                {
                    removeDatabaseNodes.Add(databaseNode);
                }
            }
            foreach (var databaseNode in removeDatabaseNodes)
            {
                treeHolistic.SelectedNode.Nodes.Remove(databaseNode);
            }
            removeDatabaseNodes.Clear();
            removeDatabaseNodes = null;


            foreach (var database in _holistic.Database)
            {
                var key = database.GetHashCode().ToString();
                if (!treeHolistic.SelectedNode.Nodes.ContainsKey(key))
                {
                    var node = treeHolistic.SelectedNode.Nodes.Add(key, database.Name);
                    node.Tag = database;
                }
            }
        }
    }
}
